package io.xxx.xbutler.core.event.job;

import com.alibaba.fastjson2.JSON;
import io.xxx.xbutler.data.ContactMapper;
import io.xxx.xbutler.data.RoomMapper;
import io.xxx.xbutler.domain.Contact;
import io.xxx.xbutler.domain.Room;
import io.xxx.xbutler.sdk.TanJingClient;
import io.xxx.xbutler.sdk.TanJingResponse;
import io.xxx.xbutler.sdk.request.PullFriendInChatRoomRequest;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * 拉另外一个机器人入群
 */
@Slf4j
@Component
@DisallowConcurrentExecution
public class BackupRobotJob extends QuartzJobBean {

    @Resource
    private TanJingClient client;

    @Resource
    private ContactMapper contactMapper;

    @Resource
    private RoomMapper roomMapper;

    @Override
    protected void executeInternal(@Nonnull JobExecutionContext context) {
        List<Room> rooms = roomMapper.findOnlyOneRobotRooms();
        for (Room room : rooms) {
            String robotId = room.getRobotId();
            Contact contact = contactMapper.findFriendContact(robotId);
            PullFriendInChatRoomRequest request = new PullFriendInChatRoomRequest();
            request.setRobotSerialNo(room.getRobotSerialNo());
            request.setChatRoomSerialNo(room.getSerialNo());
            request.setFriendSerialNos(Collections.singletonList(contact.getSerialNo()));
            TanJingResponse response = client.execute(request);
            if (response.isSuccess()) {
                log.info("邀请机器人入群成功[roomId:{}, inviterId:{}, inviteeId:{}]",
                        room.getId(), robotId, contact.getId());
            } else {
                log.info("邀请机器人入群失败[roomId:{}, inviterId:{}, inviteeId:{}, response:{}]",
                        room.getId(), robotId, contact.getId(), JSON.toJSONString(response));
            }
        }
    }
}
